﻿using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using vueweb;

namespace Microsoft.AspNetCore.DataProtection
{
	public static class IDataProtectionEx
	{
		private const string DataProtectionKeysName = "DataProtection-Keys";
		
		public static IDataProtectionBuilder PersistKeysToServiceStackRedis(this IDataProtectionBuilder builder, SentinelConfig sentinelCfg, string key = DataProtectionKeysName)
		{			
			if (builder == null)
			{
				throw new ArgumentNullException("builder");
			}
			if (sentinelCfg == null)
			{
				throw new ArgumentNullException("sentinelCfg");
			}
			
			return PersistKeysToStackExchangeRedisInternal(builder, sentinelCfg, key);
		}		

		private static IDataProtectionBuilder PersistKeysToStackExchangeRedisInternal(IDataProtectionBuilder builder, SentinelConfig sentinelCfg, string key)
		{			
			OptionsServiceCollectionExtensions.Configure<KeyManagementOptions>(builder.Services, (Action<KeyManagementOptions>)delegate (KeyManagementOptions options)
			{				
				options.XmlRepository = new RedisXmlRepository(new RedisClientsManagerWrap(sentinelCfg), key);
			});
			return builder;
		}
	}
}
